package com.smart.sso.server.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import com.smart.mvc.service.mybatis.impl.ServiceImpl;
import com.smart.sso.server.dao.RoleAppDao;
import com.smart.sso.server.model.App;
import com.smart.sso.server.model.RoleApp;
import com.smart.sso.server.service.AppService;
import com.smart.sso.server.service.RoleAppService;

@Service("roleAppService")
public class RoleAppServiceImpl extends ServiceImpl<RoleAppDao, RoleApp, Integer>
	implements RoleAppService{

	@Resource
	AppService appService;
	
	@Override
	public List<RoleApp> findByRoleAppId(Integer roleId, Integer appId) {
		// TODO Auto-generated method stub
		return dao.findByRoleAppId(roleId, appId);
	}

	@Transactional
	public void allocate(Integer roleId, List<Integer> appIdList) {
		// TODO Auto-generated method stub
		dao.deleteByRoleIds(Arrays.asList(roleId));
		
		List<RoleApp> list = new ArrayList<RoleApp>();
		Integer appId;
		for(Iterator<Integer> iter = appIdList.iterator() ; iter.hasNext() ; list.add(new RoleApp(roleId , appId))) {
			appId = iter.next();
		}
		
		if(!CollectionUtils.isEmpty(list)) {
			super.save(list);
		}
	}

	@Override
	public void add(Integer roleId, Integer appId) {
		// TODO Auto-generated method stub
		dao.insert(new RoleApp(roleId , appId));
	}
	
	@Override
	public void deleteByRoleIds(List<Integer> idList) {
		// TODO Auto-generated method stub
		dao.deleteByRoleIds(idList);
	}

	@Override
	public List<App> findByRoleId(Integer roleId) {
		// TODO Auto-generated method stub
		List<App> apps = new ArrayList<App>();
		List<RoleApp> listRe = findByRoleAppId(roleId, null);
		for(int i =0 ; i <listRe.size() ; i++) {
			int appId = listRe.get(i).getAppId();
			apps.add(appService.get(appId));
		}
		return apps;
	}

	@Override
	public void deleteByAppIds(List<Integer> idList) {
		// TODO Auto-generated method stub
		dao.deleteByAppIds(idList);
	}

	@Autowired
	public void setDao(RoleAppDao dao) {
		// TODO Auto-generated method stub
		this.dao = dao;
	}

}
